package com.lagou.edu.controller;

import com.lagou.edu.pojo.LagouToken;
import com.lagou.edu.service.LagouUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: Tao Zheng
 * @classNmae: UserController
 * @packageName: com.lagou.edu.controller
 * @description:
 * @DATE: 2021/9/7 16:37
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private LagouUserService lagouUserService;


    /**
     * 用户注册
     * @param response
     * @param email
     * @param password
     * @param code
     * @return
     */
    @GetMapping("/register/{email}/{password}/{code}")
    public boolean register(HttpServletResponse response, @PathVariable("email")String email, @PathVariable("password")String password, @PathVariable("code") String code){
        if (email == null | password == null | code == null){
            return true;
        }else {
            System.out.println("-----------------------开始注册流程---------------------");
            LagouToken lagouToken = lagouUserService.register(email, password, code);
            if (lagouToken != null){
                response.addCookie(new Cookie("token",lagouToken.getToken()));
            }
        }
        return false;
    }

    /**
     * 查询该邮件是否被注册
     * @param email
     * @return
     */
    @GetMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable("email") String email){
        if (email != null){
            boolean isRegistered = lagouUserService.isRegistered(email);
            return isRegistered;
        }
        return false;
    }

    /**
     * 用户登录
     * @param response
     * @param email
     * @param password
     * @return
     */
    @GetMapping("/login/{email}/{password}")
    public boolean login(HttpServletResponse response,@PathVariable("email")String email, @PathVariable("password")String password ){
        if (email == null | password == null ){
            return false;
        }else {
            System.out.println("-----------------------开始注册流程---------------------");
            LagouToken lagouToken = lagouUserService.login(email, password);
            if (lagouToken != null){
                response.addCookie(new Cookie("token",lagouToken.getToken()));
                return true;
            }
        }
        return false;
    }

    /**
     * 根据token查询用户登录邮箱
     * @param token
     * @return
     */
    @GetMapping("/getEmail/{token}")
    public String getEmailByToken(@PathVariable String token) {
        return lagouUserService.getEmailByToken(token);
    }

}
